//
//  HomeViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/15.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "HomeViewController.h"
#import "SearchViewController.h"
#import "SDCycleScrollView.h"
#import "IndustryViewController.h"
#import "ShopViewController.h"
#import "DAPagesContainer.h"
#import "SelecedViewController.h"
#import "AppDelegate.h"
#import "UIView+Extend.h"
#import "CycleModel.h"
#import "OSSHelper.h"

@interface HomeViewController ()<SDCycleScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)SDCycleScrollView *cycleView;
@property(nonatomic,strong)ShopViewController *shopVCtrl;
@property(nonatomic,strong)IndustryViewController *indutryVCtrl;
@property(strong, nonatomic)DAPagesContainer *pagesContainer;

@property(nonatomic,strong)NSMutableArray *picArr;//轮播图oss
@property(nonatomic,strong)NSMutableArray *pathArr;//轮播图本地
@property(nonatomic,strong)NSMutableArray *urlArray;//跳转的url
@end

@implementation HomeViewController

-(instancetype)init{
    self = [super init];
    if(self){
        //监听子视图滑动情况
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(scrollToBottom) name:@"scrollToBottom" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(scrollToTop) name:@"scrollToTop" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setCityName) name:@"cityInfo" object:nil];
        //本地路径。创建文件夹
        NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/HomeLunboPhotos"];
        BOOL is= [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
        if(is){
            DLog(@"目录创建成功 ");
        }else{
            DLog(@"目录已存在 ");
        }
        self.pathArr = [NSMutableArray array];

    }
    return self;
}

- (void)scrollToBottom{
    CGFloat  cycleViewHeight =self.cycleView.height;
    [UIView animateWithDuration:.5 animations:^{
        self.cycleView.top =-cycleViewHeight;
        self.pagesContainer.view.top=56-3;
    }];
}

- (void)scrollToTop{
    CGFloat  cycleViewHeight =self.cycleView.height;
    [UIView animateWithDuration:.5 animations:^{
        self.cycleView.top =56-4-4;
        self.pagesContainer.view.top=cycleViewHeight+56-4-4;
    }];
}

-(void)setCityName{
//    UIButton *locationButton = (UIButton*)self.rightItem;
//    NSString *cityName  = [AppDelegate appDealegate].cityName;
//    if([cityName containsString:@"市"]){
//        cityName = [cityName substringToIndex:cityName.length-1];
//    }
//    [locationButton setTitle:cityName forState:UIControlStateNormal];
//    if(locationButton.currentTitle.length==2){//eg:北京
//        [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(-3, -10, 0, 0)];
//    }
//    if(locationButton.currentTitle.length==4){//eg:乌鲁木齐
//        [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(-3, -26, 0, 0)];
//    }
//    if(locationButton.currentTitle.length==3){//eg:石家庄
//        [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(-3, -18, 0, 0)];
//    }

}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.pagesContainer){
        self.pagesContainer.pageType = DAPagesContainerHome;
        DLog(@"当前pageType---DAPagesContainerHome");
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //返回按钮
    [self backButton];
    // 自定义导航栏搜索框视图
    [self customSearchButton];
    //城市选择按钮
//    [self initLocationButton];
  
    //轮播图
    [self cyleVIew];
    //分段空控件
    [self daPageCtrl];
    [self.view bringSubviewToFront:self.naviBar];
    
    //加载轮播图
    [self loadImages];
}

-(void)loadImages{
    __weak typeof(self) weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:HOMELUNBOTU paramters:nil afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"首页轮播图-----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *pics = resultDic[@"data"];
            if([pics isKindOfClass:[NSNull class]]) return ;
            if(pics.count){
                weakSelf.picArr = [NSMutableArray array];
                for(NSDictionary *dic in pics){
                    CycleModel *model = [[CycleModel alloc]init];
                    model.pic = dic[@"name"];
                    model.no =dic[@"no"];
                    [weakSelf.urlArray addObject:dic[@"url"]];
                    [weakSelf.picArr addObject:model];
                }
                [self loadIamge];
            }

        }
    }];
}
//加载轮播图图片
-(void)loadIamge{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *objectKey ;
        for(int i = 0;i<self.picArr.count;i++){
            CycleModel *model = self.picArr[i];
            objectKey =[NSString stringWithFormat:@"%@%@",@"common/slideshow/",model.pic];
            [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:objectKey xOssProcess:[NSString stringWithFormat:@"image/resize,m_fill,w_%d,h_%d",(int)(Main_Screen_Width),(int)(Main_Screen_Width/2.28)]  downLoadBlock:^(NSData *data) {
                //保存到本地
                [weakSelf saveTolocal:data index:i];
            }];
        }
    });
}
-(void)saveTolocal:(NSData*)imageData index:(int)index{
    NSString *imageName ;
    UIImage *image= [UIImage imageWithData:imageData];
    if(UIImagePNGRepresentation(image)){//返回为png图像
        imageName = [NSString stringWithFormat:@"%@.png",[self getTimeNow]];
    }else{ //返回为JPEG图像
        imageName = [NSString stringWithFormat:@"%@.jpg",[self getTimeNow]];
    }
    //本地路径
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/HomeLunboPhotos"];
    //创建文件
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%@",imageName]];
    BOOL isSuccess= [[NSFileManager defaultManager] createFileAtPath:path contents:imageData attributes:nil];
    if(!isSuccess){
        NSLog(@"失败");
    }
    DLog(@"path---%@",path);
    if(isSuccess){
        //回到主线城刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.pathArr addObject:path];
            if(self.pathArr.count==self.picArr.count){
                self.cycleView.localizationImageNamesGroup = self.pathArr;
            }
        });
    }
}
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%d", date,last];
    DLog(@"当前时间%@", timeNow);
    return timeNow;
}


- (void)daPageCtrl{
    NSMutableArray *controllersArray = [NSMutableArray array];
    self.shopVCtrl = [[ShopViewController alloc]init];
    self.shopVCtrl.masterViewControllerForPush = self;
    self.shopVCtrl.title = @"商场";
    [controllersArray addObject:self.shopVCtrl];
    
    self.indutryVCtrl = [[IndustryViewController alloc]init];
    self.indutryVCtrl.masterViewControllerForPush = self;
    self.indutryVCtrl.title = @"行业";
    [controllersArray addObject:self.indutryVCtrl];
    [self setUpPagesContainersWithChildControllers:controllersArray];
}
-(void)setUpPagesContainersWithChildControllers:(NSArray *)controllers {
    self.pagesContainer = [[DAPagesContainer alloc] init];
    [self.pagesContainer willMoveToParentViewController:self];
     self.pagesContainer.view.frame = CGRectMake(0, self.cycleView.bottom, Main_Screen_Width, Main_Screen_Height);
    self.pagesContainer.pageIndicatorColor = DEF_COLOR;
    self.pagesContainer.pageItemsTitleColor = [UIColor colorWithRed:102./255 green:102./255 blue:102./255 alpha:1.];
    self.pagesContainer.topBarBackgroundColor = [UIColor whiteColor];
    self.pagesContainer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.pagesContainer.topBarHeight = 44;
    [self.view addSubview:self.pagesContainer.view];
    [self.pagesContainer didMoveToParentViewController:self];
    self.pagesContainer.viewControllers = controllers;
    self.pagesContainer.pageType = DAPagesContainerHome;
}

- (void)cyleVIew{
    //设置轮播图高度与屏幕的宽度的比例关系
    CGFloat cycleScrollViewScale = 2.28;
    CGFloat topViewHeight = Main_Screen_Width/cycleScrollViewScale;
    //轮播图
    self.cycleView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, kNaviBarHeight-4-4, Main_Screen_Width, topViewHeight)];
    self.cycleView.backgroundColor = [UIColor clearColor];
    self.cycleView.currentPageDotImage = [UIImage imageNamed:@"lunbodian_nor"];
    self.cycleView.pageDotImage = [UIImage imageNamed:@"lunbodian_sel"];
    self.cycleView.autoScrollTimeInterval = 4.0;
    [self.view addSubview:self.cycleView];
    self.cycleView.delegate =self;
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSString *url = self.urlArray[index];
    if([url isKindOfClass:[NSNull class]]||!url.length){
        return;
    }
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

//定位位置
- (void)initLocationButton{
    UIButton *locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    locationButton.frame=CGRectMake(0, 0, 50, 40);
//    [locationButton setImage:[UIImage imageNamed:@"nav_icon_diquxiala_nor"] forState:UIControlStateNormal];
    [locationButton setTitle:@"这是哪？" forState:UIControlStateNormal];
    locationButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [locationButton setImageEdgeInsets:UIEdgeInsetsMake(-3, 42, 0, 0)];

    if(locationButton.currentTitle.length==2){//eg:北京
        [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(-3, -10, 0, 0)];
    }
    if(locationButton.currentTitle.length==4){//eg:乌鲁木齐
        [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(-3, -26, 0, 0)];
    }
    if(locationButton.currentTitle.length==3){//eg:石家庄
        [locationButton setTitleEdgeInsets:UIEdgeInsetsMake(-3, -18, 0, 0)];
    }
    [locationButton setTitleColor:DEF_COLOR  forState:UIControlStateNormal];
    [locationButton addTarget:self action:@selector(locationAction) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem =locationButton;
}

//导航栏搜索按钮
- (void)customSearchButton{
    UIImage *image =   [UIImage imageNamed:@"nav_icon_sousuo_nor"];
    UIImageView *imageV = [[UIImageView alloc]initWithImage:image];
    imageV.frame = CGRectMake(45, 0, image.size.width, image.size.height);
      imageV.centerY = self.naviBar.centerY+8;
    [self.naviBar addSubview:imageV];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(imageV.right+2, 0, 0, 0)];
    label.text =@"搜索商品或店铺";
    label.font =[UIFont systemFontOfSize:16];
    label.textColor =DEF_COLOR242;
    [label sizeToFit];
    label.centerY = self.naviBar.centerY+8;
    [self.naviBar addSubview:label];
    
    UIButton *searchButton= [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(0, 0, Main_Screen_Width-80, 24);
    [searchButton setBackgroundImage:[UIImage imageNamed:@"shouye_sousuokuang"] forState:UIControlStateNormal];
      [searchButton addTarget:self action:@selector(jumpToSearch) forControlEvents:UIControlEventTouchUpInside];
    searchButton.left = 40;
    searchButton.centerY = self.naviBar.centerY+8;
    [self.naviBar addSubview:searchButton];
}
//跳转到搜索页面
- (void)jumpToSearch{
    SearchViewController *searchViewController = [[SearchViewController alloc]init];
    searchViewController.isModel = YES;
    BaseNavigationViewController *selectedIPNavi = [[BaseNavigationViewController alloc]initWithRootViewController:searchViewController];
    [self presentViewController:selectedIPNavi animated:YES completion:nil];
}

//跳转到位置页面
- (void)locationAction{
    
    
    
}

//首页添加返回按钮
- (void)backButton{
    UIImage *image = SetImage(@"nav_icon_back_nor");
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(8, 18, 25, 40)];
    [btn addTarget:self action:@selector(backBtn) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:image forState:UIControlStateNormal];
    [self.naviBar addSubview:btn];
}
-(void)backBtn{
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismiss" object:nil];
//    [self dismissViewControllerAnimated:YES completion:nil];
    SelecedViewController *selectedViewConteroller = [[SelecedViewController alloc]init];
    BaseNavigationViewController *navi = [[BaseNavigationViewController alloc]initWithRootViewController:selectedViewConteroller];
    [[AppDelegate appDealegate].window setRootViewController:navi];
}

-(NSMutableArray *)urlArray{
    if(_urlArray==nil){
        _urlArray = [NSMutableArray array];
    }
    return _urlArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
